package validation

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	chTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
	"time"
	"wwgin/global/variable"
)

//全局的gin参数验证翻译器,支持中文和英文

func TransInit(local string) (err error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		//注册字段的别名
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("label"), ",", 2)[0]
			if name == "-" {
				return "l"
			}
			return name
		})
		zhT := zh.New() //中文
		enT := en.New() //英文
		uni := ut.New(enT, zhT, enT)
		var o bool
		variable.Trans, o = uni.GetTranslator(local)
		if !o {
			return fmt.Errorf("uni.GetTranslator(%s) failed", local)
		}
		//register translate  // 注册翻译器
		switch local {
		case "en":
			err = enTranslations.RegisterDefaultTranslations(v, variable.Trans)
		case "zh":
			err = chTranslations.RegisterDefaultTranslations(v, variable.Trans)
		default:
			err = chTranslations.RegisterDefaultTranslations(v, variable.Trans)
		}

		//注册一个自定义的时间验证器
		e := v.RegisterValidation("TimeValid", TimeValid)
		if e != nil {
			return fmt.Errorf("验证器TimeValid注册失败", local)
		}

		//根据提供的标记注册翻译
		_ = v.RegisterTranslation("TimeValid", variable.Trans, func(ut ut.Translator) error {
			return ut.Add("TimeValid", "{0}格式错误", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("TimeValid", fe.Field(), fe.Field())
			return t
		})

		return
	}
	return
}

//自定义验证器
func TimeValid(fl validator.FieldLevel) bool {
	if date, ok := fl.Field().Interface().(string); ok {
		_, err := time.Parse("2006-01-02 15:04:05", date)
		if err != nil {
			return false
		}
	}
	return true
}
